/*
 * @Date: 2023-03-09 17:39:36
 * @LastEditors: mengqingchen mengqc1995@163.com
 * @LastEditTime: 2023-03-10 10:57:19
 * @FilePath: \vite-vue3-ts\src\router\index.ts
 */
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

import exceptionRoutes from '@/router/routeException'
import asyncRoutes from '@/router/routeAsync'
import commonRoutes from '@/router/routeCommon'

export const constantRoutes: Array<RouteRecordRaw> = [
  // 无鉴权的业务路由 ex:登录
  ...commonRoutes,
  // 带鉴权的业务路由
  ...asyncRoutes,
  // 异常页必须放在路由匹配规则的最后
  ...exceptionRoutes
]

const router = createRouter({
  // 新的vue-router4 使用 history路由模式 和 base前缀
  history: createWebHistory(import.meta.env.VITE_BASE),
  routes: constantRoutes,
  // 每次切换路由页面滚动到顶部
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || import.meta.env.VITE_APP_TITLE

  next()
})
router.afterEach((to, from) => {
  console.log('全局路由后置守卫：to,from\n', to, from)
})

/** 解决跳转重复路由报错问题 */
const routerPush = router.push
router.push = (path: string): any => {
  // 判断下当前路由是否就是要跳转的路由
  if (router.currentRoute.value.fullPath.includes(path)) {
    return
  }
  return routerPush.call(router, path)
}

export default router
